/*
	Copyright (c) 2004 Cory Nelson

	Permission is hereby granted, free of charge, to any person obtaining
	a copy of this software and associated documentation files (the
	"Software"), to deal in the Software without restriction, including
	without limitation the rights to use, copy, modify, merge, publish,
	distribute, sublicense, and/or sell copies of the Software, and to
	permit persons to whom the Software is furnished to do so, subject to
	the following conditions:

	The above copyright notice and this permission notice shall be included
	in all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
	MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
	IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
	CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
	TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
	SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "gamestat.h"
#include "internal.h"

typedef unsigned char* (*getdata_cb)(unsigned char*); // return pointer to data if packet is valid
typedef void (*parseserver_cb)(GS_SERVER*, unsigned char**);

static unsigned char q3_recieve(SOCKET s, GS_SERVER **servers, GS_SERVER **curserver, getdata_cb getdata, parseserver_cb parseserver) {
	size_t packetlen;
	unsigned char *packet;
	unsigned char *iter, *end;

	packet=(unsigned char*)getpacket(s, &packetlen);
	if(!packet) {
		lasterror=GS_ERROR_TIMEOUT;
		return 0;
	}

	dbg_dumpbuf("quake3_master.bin", packet, packetlen);

	iter=getdata(packet);
	if(!iter) {
		lasterror=GS_ERROR_CORRUPT;
		free(packet);
		return 0;
	}
	end=packet+packetlen;

	while(iter<end) {
		if(iter[0]=='E' && iter[1]=='O' && iter[2]=='T' && iter[3]=='\0') {
			free(packet);
			return 1;
		}
		else if(iter[0]=='E' && iter[1]=='O' && iter[2]=='F' && iter[3]=='\0') {
			free(packet);
			return 2;
		}
		else {
			GS_SERVER *server=malloc(sizeof(GS_SERVER));
			server->next=NULL;

			parseserver(server, &iter);

			if(*curserver) *curserver=(*curserver)->next=server;
			else *curserver=*servers=server;

			iter++;
		}
	}

	free(packet);
	return 0;
}

static GS_SERVER *__querymaster_quake3(const char *host, unsigned short port, unsigned short protocol, unsigned short filter, const char *filterextra, getdata_cb getdata, parseserver_cb parseserver) {
	char sendbuf[64];
	SOCKET s=getsockudp(host, port);
	GS_SERVER *servers=NULL, *curserver=NULL;

	if(s==INVALID_SOCKET) return NULL;

	sprintf(sendbuf, "\xFF\xFF\xFF\xFFgetservers %hu%s", protocol, filterextra);
	if(filter&GS_MASTER_FILTER_EMPTY) strcat(sendbuf, " empty");
	if(filter&GS_MASTER_FILTER_FULL) strcat(sendbuf, " full");

	if(send(s, sendbuf, (int)strlen(sendbuf), 0)==SOCKET_ERROR) {
		closesocket(s);
		lasterror=GS_ERROR_TIMEOUT;
		return NULL;
	}

	while(1) {
		switch(q3_recieve(s, &servers, &curserver, getdata, parseserver)) {
			case 0:
				closesocket(s);
				return servers;
			case 2:
				closesocket(s);
				lasterror=GS_OK;
				return servers;

		}
	}
}

//////////////////////////////////////////////////////////////
// Quake 3

typedef struct {
	int check;
	char check2[19];
	unsigned char data[1];
} QUAKE3_PACKET;

static unsigned char *q3_getdata(unsigned char *packet) {
	QUAKE3_PACKET *p=(QUAKE3_PACKET*)packet;

	p->check2[18]='\0';
	if(swapint32(p->check)!=-1 || strcmp(p->check2, "getserversResponse")) return NULL;
	else return p->data;
}

static void q3_parseserver(GS_SERVER *server, unsigned char **data) {
	char host[16];

	sprintf(host, "%d.%d.%d.%d", (int)(*data)[0], (int)(*data)[1], (int)(*data)[2], (int)(*data)[3]); (*data)+=sizeof(unsigned int);
	server->host=strdup(host);

	server->port=ntohs(((unsigned short*)(*data))[0]); (*data)+=sizeof(unsigned short);
}

GS_SERVER *querymaster_quake3(const char *host, unsigned short port, unsigned short protocol, unsigned short filter) {
	return __querymaster_quake3(host, port, protocol, filter, "", q3_getdata, q3_parseserver);
}

//////////////////////////////////////////////////////////////
// Soldier of Fortune 2, Jedi Knight 2

typedef struct {
	int check;
	char check2[21];
	unsigned char data[1];
} SOF2_PACKET;

static unsigned char *sof2_getdata(unsigned char *packet) {
	SOF2_PACKET *p=(SOF2_PACKET*)packet;

	p->check2[18]='\0';
	if(swapint32(p->check)!=-1 || strcmp(p->check2, "getserversResponse")) return NULL;
	else return p->data;
}

GS_SERVER *querymaster_sof2(const char *host, unsigned short port, unsigned short protocol, unsigned short filter) {
	return __querymaster_quake3(host, port, protocol, filter, " SOF2FULL", sof2_getdata, q3_parseserver);
}

GS_SERVER *querymaster_swjk2(const char *host, unsigned short port, unsigned short protocol, unsigned short filter) {
	return __querymaster_quake3(host, port, protocol, filter, "", sof2_getdata, q3_parseserver);
}

//////////////////////////////////////////////////////////////
// Star Trek Voyager

typedef struct {
	int check;
	char check2[20];
	char data[1];
} STVEF_PACKET;

static unsigned char *stvef_getdata(unsigned char *packet) {
	STVEF_PACKET *p=(STVEF_PACKET*)packet;

	p->check2[18]='\0';
	if(swapint32(p->check)!=-1 || strcmp(p->check2, "getserversResponse")) return NULL;
	else return p->data;
}

static void stvef_parseserver(GS_SERVER *server, unsigned char **data) {
	char host[16];
	int ip1, ip2, ip3, ip4, port;

	sscanf((char*)(*data), "%2x%2x%2x%2x%4x", &ip1, &ip2, &ip3, &ip4, &port); (*data)+=12;

	sprintf(host, "%d.%d.%d.%d", ip1, ip2, ip3, ip4);
	server->host=strdup(host);

	server->port=(unsigned short)port;
}

GS_SERVER *querymaster_stvef(const char *host, unsigned short port, unsigned short protocol, unsigned short filter) {
	return __querymaster_quake3(host, port, protocol, filter, "", stvef_getdata, stvef_parseserver);
}
